function newq=mergePart(q, top, left, s, type)
    if nargin == 4
        type = 1;
    end
    
    if type == 1
        newq = mergePart1(q, top, left, s);
    else
        newq = mergePart2(q, top, left, s);
    end
end

function newq=mergePart1(q, top, left, s)
    sq = idct2(s,8,8)+128;
    bq0 = idct2(q(1:8,1:8),8,8)+128;
    bq1 = idct2(q(1:8,9:16),8,8)+128;
    bq2 = idct2(q(9:16,1:8),8,8)+128;
    bq3 = idct2(q(9:16,9:16),8,8)+128;
    bq = [bq0,bq1;bq2,bq3];
    bq(top:top+7,left:left+7) = sq;
    q0=dct2(bq(1:8,1:8)-128,8,8);
    q1=dct2(bq(1:8,9:16)-128,8,8);
    q2=dct2(bq(9:16,1:8)-128,8,8);
    q3=dct2(bq(9:16,9:16)-128,8,8);
    newq = [q0, q1; q2, q3];
end

function newq=mergePart2(q, top, left, s)
    % q is 16x16 matrix, top, left is the position of DCT Coef
    q0=q(1:8,1:8);
    if (top==1)&&(left==1)
        newq=s;
        return;
    end
    q1=q(1:8,9:16);
    q2=q(9:16,1:8);
    q3=q(9:16,9:16);

    sx = extractPart(q, top, left)
    s = s-sx;
 
    s0a=hxMAT(top-1);
    s0b=hxMAT(left-1)';
    s0 = s0a*s*s0b
    
    s1a=hxMAT(top-1);
    s1b=hxMAT(9-left)';
    s1 = s1a*s*s1b;
    
    s2a=hxMAT(9-top);
    s2b=hxMAT(left-1)';
    s2 = s2a*s*s2b;
    
    s3a=hxMAT(9-top);
    s3b=hxMAT(9-left)';
    s3 = s3a*s*s3b;
        
    newq = [q0+s0,q1+s1;q2+s2,q3+s3];
end

function ret = hxMAT_A(dimension)
    z = zeros(8,8);
    z(1:dimension,1:dimension)=eye(dimension);
    ret = z;
    %ret = dct2(z, 8, 8);
end

function ret = hxMAT_B(dimension)
    z = zeros(8,8);
    z(9-dimension:8,9-dimension:8)=eye(dimension);
    ret = z;
    %ret = dct2(z, 8, 8);
end

function ret = hxMAT(dimension)
    z = zeros(8,8);
    z(1:dimension,9-dimension:8)=eye(dimension);
    ret = z;
    %ret = dct2(z, 8, 8);
end
